﻿using System;
using System.Collections.Generic;
using System.Linq;
using IcsSEMCtrl.Event;
using Lifter.Event.Lifter;
using Lifter.Gui.Widget;
using IcsSEMCtrl.Db;
using System.Data.SqlClient;
using IcsSEMCtrl.Service.Logger;
using Lifter.Device;
using IcsSEMCtrl.Util.Server;
using Lifter.Utility;
using Lifter.Global.Device;
using TKT.Lifter.CIM.Lifter.Event.Lifter;
using Sunny.UI;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;
using TKT.Lifter.CIM.Lifter.Global;
using System.Threading.Tasks;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Device.Unit;

namespace Lifter.Gui.Monitor.Panels
{
    public partial class MainLayoutUI : OPPanel
    {
        private delegate void delegateUpdateForm();
        private class VehicleEventAdapter : ECPEventAdapter
        {
            public VehicleEventAdapter()
            {
                base.Subscribe();
            }
            public override string GetSubscriptionSubject()
            {
                return VehicleLocationEvent.FormSubject("*");
            }
            public override void ReceiveECPEvent(ECPEvent ecpEvent)
            {
                MainLayoutUI.UpdateVehicleLocation(ecpEvent);
            }
        }
        private class SensorEventAdapter : ECPEventAdapter
        {
            public SensorEventAdapter()
            {
                base.Subscribe();
            }
            public override string GetSubscriptionSubject()
            {
                return SensorEvent.FormSubject("*");
            }
            public override void ReceiveECPEvent(ECPEvent ecpEvent)
            {
                MainLayoutUI.UpdateSensor(ecpEvent);
            }
        }

        private static Dictionary<string, MainLayoutUI> OperationPanelByName = new Dictionary<string, MainLayoutUI>();
        private static MainLayoutUI.VehicleEventAdapter vehicleEventAdapter = null;
        private static MainLayoutUI.SensorEventAdapter sensorEventAdapter = null;
        private LifterSEM lifterSem = null;
        private string vehicleId = "VEHICLE:1";
        private short vehicleLoc = 1;
        private string sensorName = "";
        private short sensorValue = 0;
        private Queue<MainLayuiSenserInfo> senserInfos = new Queue<MainLayuiSenserInfo>();
        private string sensor2FW1Name = "";
        private short sensor2FW1Value = 0;
        private double shuttleLocation;//轿厢实时位置
        public string VehicleId
        {
            get
            {
                return this.vehicleId;
            }
            set
            {
                this.vehicleId = value;
            }
        }
        public short VehicleLoc
        {
            get
            {
                return this.vehicleLoc;
            }
            set
            {
                this.vehicleLoc = value;
            }
        }

        public MainLayoutUI()
        {
            InitializeComponent();
            SimpleCache.AddObject("FormMain", "UserManageControl", this.userManageControl);
            this.materialInfoControl1.dgvMaterialInfo.ScrollBars = ScrollBars.Both;
            this.mainTransferQueuePanel1.dgvTansferComandShow.ScrollBars = ScrollBars.Both;

            this.EventsHandlerReg();
            this.Subscribe();
            //this.InitTowerFloor();
            //this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

            this.LayoutSetup();
            this.shuttleLocationMove();
        }
        /// <summary>
        /// 绘制Layout方法,李浩宇新增,2023.11.28
        /// </summary>
        private void LayoutSetup()
        {
            //创建LoadMainLayout对象
            LoadMainLayout loadMainLayout = LoadMainLayout.getLoadMainLayout();

            foreach (BMDTLifterPortWidget bMDTLifterPortWidget in loadMainLayout.controlPortList)
            {
                //绘制控件
                bMDTLifterPortWidget.Location = new Point(bMDTLifterPortWidget.axis_X, bMDTLifterPortWidget.axis_Y);//坐标

                //对比数据表尺寸和控件尺寸,如果配置尺寸大于默认尺寸则采用配置尺寸
                if (bMDTLifterPortWidget.width > bMDTLifterPortWidget.Width && bMDTLifterPortWidget.height > bMDTLifterPortWidget.Height)
                {
                    bMDTLifterPortWidget.Size = new Size(bMDTLifterPortWidget.width, bMDTLifterPortWidget.height);
                }

                CVPortPanel.Controls.Add(bMDTLifterPortWidget);
            }

            foreach (CnvBuffer cnvBuffer in loadMainLayout.controlCVList)
            {
                //绘制控件
                cnvBuffer.Location = new Point(cnvBuffer.axis_X, cnvBuffer.axis_Y);//坐标
                //对比数据表尺寸和控件尺寸,如果配置尺寸大于默认尺寸则采用配置尺寸
                if (cnvBuffer.width > cnvBuffer.Width && cnvBuffer.height > cnvBuffer.Height)
                {
                    cnvBuffer.Size = new Size(cnvBuffer.width, cnvBuffer.height);
                }

                CVPortPanel.Controls.Add(cnvBuffer);
            }

            foreach (VehicleWidget vehicleWidget in loadMainLayout.controlVehicleList)
            {
                //绘制控件
                vehicleWidget.Location = new Point(vehicleWidget.axis_X, vehicleWidget.axis_Y);//坐标
                //对比数据表尺寸和控件尺寸,如果配置尺寸大于默认尺寸则采用配置尺寸
                if (vehicleWidget.width > vehicleWidget.Width && vehicleWidget.height > vehicleWidget.Height)
                {
                    vehicleWidget.Size = new Size(vehicleWidget.width, vehicleWidget.height);
                }

                VehiclePanel.Controls.Add(vehicleWidget);
            }

        }
        
        public void DoShuttleLocationMove()
        {
            Dictionary<int, FloorDao> floors = Floor.getFloor().getFloors();
            int shuttleLocFromPLC = 0;
            if (floors != null && floors.Count > 0)
            {
                this.lifterSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
                while (true)
                {
                    shuttleLocFromPLC = this.lifterSem.ShuttleMaster.I_SHUTTLELOCATION / 10;
                    foreach (KeyValuePair<int,FloorDao> keyValuePair in floors)
                    {
                        double startHight = Convert.ToDouble(keyValuePair.Value.FloorStartHight);
                        double endHight = Convert.ToDouble(keyValuePair.Value.FloorEndHight);
                        double ratio = Convert.ToDouble(keyValuePair.Value.Ratio);
                        int floor = keyValuePair.Value.FloorID;
                        double floorHight = Convert.ToDouble(keyValuePair.Value.FloorHight);

                        if (shuttleLocFromPLC >= startHight && shuttleLocFromPLC <= endHight)
                        {
                            shuttleLocation = this.LifterPanel.Height - (this.VehiclePanel.Height + 14) + (-237 * (floor - 1) + (-ratio * (shuttleLocFromPLC - startHight)));
                            this.VehiclePanel.Invalidate();
                            break;
                        }
                    }
                    Thread.Sleep(200);
                }
            }
/*            //每层高237像素，轿厢高度220像素，离顶部底部14像素
            this.lifterSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            double num = -237 / 1279.00; // (double)(((double)this.LifterPanel.Height) - 28.00) / 1279.00;
            int shuttleLocFromPLC = 0;
            //获取PLC轿厢实时位置
            while (true)
            {
                shuttleLocFromPLC = this.lifterSem.ShuttleMaster.I_SHUTTLELOCATION / 10;
                
                if (shuttleLocFromPLC <= 1279.00 && shuttleLocFromPLC >= 0)
                {
                    shuttleLocation = 948 - 220 - 14 + num * ((double)shuttleLocFromPLC);
                }
                this.VehiclePanel.Invalidate();
                Thread.Sleep(200);
            }*/
        }
        public void shuttleLocationMove()
        {
            Task.Run(this.DoShuttleLocationMove);
        }
        private void VehiclePanel_Paint(object sender, PaintEventArgs e)
        {
            this.VehiclePanel.Location = new Point(20, Convert.ToInt32(shuttleLocation));
        }
        private void EventsHandlerReg()
        {
            SimpleCache.AddObject("OperationForm", "MainTransferQueuePanel", this.mainTransferQueuePanel1);
            //SimpleCache.AddObject("OperationForm", "MainVehicleState", this.mainVehicleState1);
            this.mainTransferQueuePanel1 = (MainTransferQueuePanel)SimpleCache.GetObject("OperationForm", "MainTransferQueuePanel");
            //绑定主页面搬送命令显示控件点击事件
            this.mainTransferQueuePanel1.Click += new MainTransferQueuePanelEvent(MonitorEventHandler.OnTransferQueueChange);
            //this.mainVehicleState1 = (MainVehicleState)SimpleCache.GetObject("OperationForm", "MainVehicleState");
            //绑定主页面轿厢状态控件点击事件
            //this.mainVehicleState1.Click += new VehiclePanelEvent(MonitorEventHandler.OnVehicleStatePanelClick);
        }
        public void Subscribe()
        {
            if (MainLayoutUI.vehicleEventAdapter == null)
            {
                MainLayoutUI.vehicleEventAdapter = new MainLayoutUI.VehicleEventAdapter();
            }
            if (MainLayoutUI.sensorEventAdapter == null)
            {
                MainLayoutUI.sensorEventAdapter = new MainLayoutUI.SensorEventAdapter();
            }
            if (!MainLayoutUI.OperationPanelByName.ContainsKey(this.vehicleId))
            {
                MainLayoutUI.OperationPanelByName.Add(this.vehicleId, this);
            }
        }
        public override void UpdatePlaybackWorkItem(string data)
        {
            this.mainTransferQueuePanel1.UpdatePlaybackWorkItem(data);
        }
        public override void UpdatePlaybackAlarmData(string data)
        {
            this.userManageControl.UpdatePlaybackAlarmData(data);
        }
        
        public static void UpdateVehicleLocation(ECPEvent ecpEvent)
        {
            VehicleLocationEvent vehicleLocationEvent = (VehicleLocationEvent)ecpEvent;
            if (MainLayoutUI.OperationPanelByName.ContainsKey(vehicleLocationEvent.VehicleId))
            {
                MainLayoutUI operationPanelLFT = MainLayoutUI.OperationPanelByName[vehicleLocationEvent.VehicleId];
                operationPanelLFT.VehicleLoc = vehicleLocationEvent.VehicleLocation;
                //operationPanelLFT.UpdateFormDelegate();
            }
        }
        public static void UpdateSensor(ECPEvent ecpEvent)
        {
            SensorEvent sensorEvent = (SensorEvent)ecpEvent;
            MainLayoutUI operationPanelLFT = MainLayoutUI.OperationPanelByName["VEHICLE:1"];
            operationPanelLFT.sensorName = sensorEvent.Name1;
            operationPanelLFT.sensorValue = sensorEvent.Value1;
            operationPanelLFT.senserInfos.Enqueue(new MainLayuiSenserInfo { Name = sensorEvent.Name1, Value = sensorEvent.Value1 });
            //operationPanelLFT.UpdateSensorDelegate();
        }
        /// <summary>
        /// 手动创建轿厢Move指令信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemMoveCommand_Click(object sender, EventArgs e)
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetLifter();
            if (!lifterSEM.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                VehicleManualMove vehicleManualMove = new VehicleManualMove();
                vehicleManualMove.ShowDialogWithMask();
                if (vehicleManualMove.IsOK)
                {
                    vehicleManualMove.CreateManualMoveCommand();
                }
                vehicleManualMove.Dispose();
            }
        }
        /// <summary>
        /// 手动创建轿厢搬送指令信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemTransferCommand_Click(object sender, EventArgs e)
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetLifter();
            if (!lifterSEM.UserPrivilige)
            {
                PopupNotice.DialogPopups("请先登录", "Please login", enumPopupsType.Warning);
            }
            else
            {
                VehicleManualTransfer vehicleManualTransfer = new VehicleManualTransfer();
                vehicleManualTransfer.ShowDialogWithMask();
                if (vehicleManualTransfer.IsOK)
                {
                    vehicleManualTransfer.CreateManualMoveCommand();
                }
                vehicleManualTransfer.Dispose();
            }
        }
        /// <summary>
        /// 轿厢详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ItemVehicleInfo_Click(object sender, EventArgs e)
        {
            ShuttleDetailInfo shuttleDetailInfo = new ShuttleDetailInfo();
            shuttleDetailInfo.ShowDialogWithMask();
        }

        private void ShuttleSensorInfo_Click(object sender, EventArgs e)
        {
            ShuttleSensorInfo shuttleSensorInfo = new ShuttleSensorInfo();
            shuttleSensorInfo.Subscribe();
            shuttleSensorInfo.Show();
            LifterSEM lftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            //初始化SensorIO信号值
            short SensorIO1F2FValue = lftSem.ShuttleMaster.I_SHUTTLE1F2FSENSORIOVALUE;
            short SensorIO3F4FValue = lftSem.ShuttleMaster.I_SHUTTLE3F4FSENSORIOVALUE;
            this.BeginInvoke(lftSem.ShuttleMaster.senser1F2FInfoDelegate, Convert.ToInt32(SensorIO1F2FValue));
            this.BeginInvoke(lftSem.ShuttleMaster.senser3F4FInfoDelegate, Convert.ToInt32(SensorIO3F4FValue));
        }
    }
    public class MainLayuiSenserInfo
    {
        public string Name { get; set; }
        public short Value { get; set; }
    }
}
